package product.interfaces.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import product.application.service.ProductService;
import product.domain.model.Product;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/products")
public class ProductController {

    @Autowired
    private ProductService productService;

    @PostMapping
    public Product create(@RequestBody Product product) {
        return productService.createProduct(product);
    }

    @GetMapping
    public List<Product> getAll() {
        return productService.getAllProducts();
    }

    // ✅ 修改：支持根据 id 更新
    @PutMapping("/{id}")
    public Product update(@PathVariable("id") Integer id, @RequestBody Product product) {
        return productService.updateProduct(id, product);
    }

    @DeleteMapping("/{id}")
    public void delete(@PathVariable("id") Integer id) {
        productService.deleteProduct(id);
    }

    @GetMapping("/{id}")
    public Optional<Product> getById(@PathVariable("id") Integer id) {
        return productService.getProductById(id);
    }

    // ✅ 新增：根据用户ID获取商品
    @GetMapping("/user/{userId}")
    public List<Product> getByUserId(@PathVariable("userId") Long userId) {
        return productService.getByUserId(userId);
    }

    // ✅ 新增：根据分类获取商品
    @GetMapping("/category/{category}")
    public List<Product> getByCategory(@PathVariable("category") String category) {
        return productService.getByCategory(category);
    }
}